package com.jack.blog.dto;

import com.jack.blog.entity.Message;
import com.jack.blog.utils.DateUtil;
import com.jack.blog.vo.MessageVo;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;

@Component
public class MessageDto extends BaseDto{

    public Message MessageVoToMessage(MessageVo messageVo)throws IllegalArgumentException{
        Message message=new Message();
        String email = messageVo.getEmail();
        String content = messageVo.getContent();
        if (content.length()>50)
            throw new IllegalArgumentException("消息内容太长!");
        if (!email.matches("[1-9][0-9]{8,10}\\@qq\\.com"))
            throw new IllegalArgumentException("请输入QQ邮箱!");
        if (email.length()>32)
            throw new IllegalArgumentException("邮箱长度超过32!");
        message.setContent(content);
        message.setEmail(email);
        message.setSendTime(DateUtil.getTimestamp());
        return message;
    }

    public MessageVo MessageToMessageVo(Message message){
        MessageVo messageVo=new MessageVo();
        String email = message.getEmail();
        messageVo.setId(message.getId());
        messageVo.setEmail(email.replaceFirst(email.substring(1, email.lastIndexOf("@") - 1),"***"));
        messageVo.setContent(message.getContent());
        messageVo.setTime(DateUtil.getStringByTimestamp(message.getSendTime(),"yyyy-MM-dd HH:mm"));
        messageVo.setReply(message.isReply());
        return messageVo;
    }

    public List<MessageVo> MessageToMessageVo(List<Message> messages){
        List<MessageVo> messageVos=new LinkedList<>();
        for (Message message:messages)
            messageVos.add(MessageToMessageVo(message));
        return messageVos;
    }
}
